package org.irri.smta.repository;

import java.util.List;

import javax.inject.Named;

import org.irri.smta.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

@Named("userRepository")
public interface IUserRepository extends JpaRepository<User, Long> {

	@Transactional(readOnly = true)
	@Query("SELECT o FROM User o ORDER BY o.username")
	List<User> findAllOrdered();

	@Transactional(readOnly = true)
	@Query("SELECT o FROM User o WHERE LOWER(o.username) = LOWER(:username) AND LOWER(o.password) = LOWER(:password)")
	List<User> findByUsernameAndPassword(@Param("username") String username,
			@Param("password") String password);

	@Modifying
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	@Query("UPDATE User o SET o.password = :newPassword WHERE o.username = :username AND o.password = :oldPassword")
	void changePassword(@Param("username") String username,
			@Param("oldPassword") String oldPassword,
			@Param("newPassword") String newPassword);

}
